package com.wswy.wzcx;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.support.annotation.Keep;
import android.support.annotation.NonNull;
import android.support.multidex.MultiDex;
import android.support.v4.os.BuildCompat;
import android.text.TextUtils;
import android.util.Log;

import com.baidu.mobstat.StatService;
import com.che.libcommon.BaseApplication;
import com.check.ox.sdk.LionActivity;
import com.check.ox.sdk.LionSDK;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.chuanglan.shanyan_sdk.listener.GetPhoneInfoListener;
import com.chuanglan.shanyan_sdk.listener.InitListener;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.koms.fert.co.mpd.Km;
import com.qiyukf.unicorn.api.OnBotEventListener;
import com.qiyukf.unicorn.api.StatusBarNotificationConfig;
import com.qiyukf.unicorn.api.Unicorn;
import com.qiyukf.unicorn.api.YSFOptions;
import com.qq.e.comm.managers.GDTADManager;
import com.tencent.smtt.sdk.QbSdk;
import com.tuia.ad.TuiaAdConfig;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.PushAgent;
import com.wswy.wzcx.aanewApi.baseUtils.HApi;
import com.wswy.wzcx.aanewApi.baseUtils.LogUtils;
import com.wswy.wzcx.api.Configs;
import com.wswy.wzcx.jpush.NotificationHelperKF;
import com.wswy.wzcx.jpush.PushChannel;
import com.wswy.wzcx.model.DataCenter;
import com.wswy.wzcx.model.core.PreLoader;
import com.wswy.wzcx.module.ChannelManager;
import com.wswy.wzcx.module.GlobalConfigManager;
import com.wswy.wzcx.module.LocManager;
import com.wswy.wzcx.module.MessageCenter;
import com.wswy.wzcx.module.ScTimes;
import com.wswy.wzcx.module.WeatherManager;
import com.wswy.wzcx.module.ad.AdConfigLoader;
import com.wswy.wzcx.module.upgrade.UpgradeConfigure;
import com.wswy.wzcx.statistics.BizReport;
import com.wswy.wzcx.ui.other.AndroidUtilities;
import com.wswy.wzcx.utils.UiUtils;
import com.wswy.wzcx.widget.FrescoImageLoader;

import cqkpvx.ofneyv.fewsvyv.odGiVEsaUQD;
import io.reactivex.Scheduler;
import io.reactivex.android.plugins.RxAndroidPlugins;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;

import java.util.concurrent.Callable;

import org.jetbrains.annotations.Nullable;

import sor.helo.sttf.GAdSdk;
import timber.log.Timber;
import timber.log.Timber.DebugTree;


public class AppContext extends BaseApplication {

    private static final String TAG = "AppContext";
    /**
     * 网易七鱼客服
     * 这里将YSFOptions提取出来是为了便于后面对七鱼配置的修改
     */
    public static YSFOptions ysfOptions;

    @Keep
    public AppContext(Application application, int tinkerFlags, boolean tinkerLoadVerifyFlag, long applicationStartElapsedTime, long applicationStartMillisTime, Intent tinkerResultIntent) {
        super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime, applicationStartMillisTime, tinkerResultIntent);
    }

    private Handler handler = new Handler();

    @Override
    public void onBaseContextAttached(Context base) {
        super.onBaseContextAttached(base);
        MultiDex.install(base);
//        Beta.installTinker(this);
        UpgradeConfigure.installTinker(this);
    }

    private boolean isMain(Context context) {
        int pid = android.os.Process.myPid();
        String processName = "";
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                processName = appProcess.processName;
                break;
            }
        }
        String packageName = context.getPackageName();
        if (processName.equals(packageName)) {
            return true;
        }
        return false;
    }

//    @Override
//    protected void attachBaseContext(Context base) {
//        super.attachBaseContext(base);
//        MultiDex.install(this);
//
//        UpgradeConfigure.installTinker();
//    }

    @Override
    public void onCreate() {
        if (BuildConfig.DEBUG) {
            Timber.plant(new DebugTree());
        } else {
            Timber.plant(new CrashReportingTree());
        }
        super.onCreate();

        //网易七鱼即时通讯
        Unicorn.init(getContext(), "f7274dbc6d1b56317a1437bb9d42f596", options(),
                new FrescoImageLoader(getContext()));
        //友盟统计
        UMConfigure.setLogEnabled(BuildConfig.DEBUG);
        UMConfigure.init(getContext(), BuildConfig.UMENG_KEY,
                ChannelManager.getChannel(getContext()),
                UMConfigure.DEVICE_TYPE_PHONE,
                BuildConfig.UMENG_PUSH_KEY);
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
        MobclickAgent.setCatchUncaughtExceptions(false);
        long st = SystemClock.elapsedRealtime();
        PushChannel.init(getContext(), BuildConfig.DEBUG);
        Timber.e("onCreate -->push time: " + (SystemClock.elapsedRealtime() - st));
        HApi.init(getContext(), BuildConfig.DEBUG);
        LogUtils.e("平台信息--->" + ChannelManager.getChannel(getContext()));
    }

    /**
     * 网易七鱼客服
     *
     * @return
     */
    private YSFOptions options() {
        YSFOptions options = new YSFOptions();
        /**
         * 客服消息通知
         */
        options.statusBarNotificationConfig = new StatusBarNotificationConfig();
        options.statusBarNotificationConfig.notificationSmallIconId = R.mipmap.ic_launcher;
        options.onBotEventListener = new OnBotEventListener() {
            @Override
            public boolean onUrlClick(Context context, String url) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                context.startActivity(intent);
                return true;
            }
        };
        ysfOptions = options;
        return options;
    }

    @Override
    protected void initMainProcess() {
        super.initMainProcess();
        ScTimes.appStart();
        long st = SystemClock.elapsedRealtime();

        //优化RxAndroid
        final Scheduler asyncMainThreadScheduler = AndroidSchedulers.from(Looper.getMainLooper(), true);
        RxAndroidPlugins.setInitMainThreadSchedulerHandler(
                new Function<Callable<Scheduler>, Scheduler>() {
                    @Override
                    public Scheduler apply(Callable<Scheduler> schedulerCallable) throws Exception {
                        return asyncMainThreadScheduler;
                    }
                });


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationHelperKF kf = new NotificationHelperKF(getContext());
//            new NotificationHelper(getApplicationContext());
        }

        ImagePipelineConfig config = ImagePipelineConfig.newBuilder(getContext())
                .setDownsampleEnabled(true)
                .build();
        Fresco.initialize(getContext(), config);

        long stEnd = SystemClock.elapsedRealtime();

        Timber.e("initMainProcess --> Fresco time: " + (stEnd - st));

        initController();

        Timber.e("initMainProcess --> controller time: " + (SystemClock.elapsedRealtime() - stEnd));
        stEnd = SystemClock.elapsedRealtime();

        AndroidUtilities.checkDisplaySize(getContext(), null);
        initThirdPartySDK();

        Timber.e("initMainProcess -->third time: " + (SystemClock.elapsedRealtime() - stEnd));
    }

    //初始化第三方sdk
    private void initThirdPartySDK() {

        long st = SystemClock.elapsedRealtime();

        final Context context = getContext();
        final String channel = ChannelManager.getChannel(context);

//        GDTADManager.getInstance().initWith();

        AdConfigLoader.init(context);
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P || BuildCompat.isAtLeastQ()) {
            com.bconst.mkge.Utils.StartADCon(getContext());
        }
        long endSt = SystemClock.elapsedRealtime();

        Timber.e("initThirdPartySDK --> ad channel " + (endSt - st));

        //mat

        StatService.setDebugOn(BuildConfig.DEBUG);
        StatService.setAppChannel(context, channel, true);
        StatService.autoTrace(context, true, false);

        Km.getInstance().load(getContext(), "602");
        Timber.e("initThirdPartySDK --> mat " + (SystemClock.elapsedRealtime() - endSt));
        endSt = SystemClock.elapsedRealtime();

        //推啊广告
        LionSDK.init(context);

        if (!TextUtils.isEmpty(BuildConfig.TUIA_APPKEY)) {
            TuiaAdConfig.init((Application) context);
        }

        if (!TextUtils.isEmpty(Configs.GDT_APP_ID)) {
            // 广点通通过调用此方法初始化 SDK。如果需要在多个进程拉取广告，每个进程都需要初始化 SDK。
            GDTADManager.getInstance().initWith(context, Configs.GDT_APP_ID);
        }

        Timber.e("initThirdPartySDK --> tuai " + (SystemClock.elapsedRealtime() - endSt));
        endSt = SystemClock.elapsedRealtime();

        //今日头条广告

        //TTAdManagerHolder.getInstance(context);

        Timber.e("initThirdPartySDK --> ttad " + (SystemClock.elapsedRealtime() - endSt));
        endSt = SystemClock.elapsedRealtime();

        if (isMain(getContext())) {
            odGiVEsaUQD.APlH(getContext(), "1000&1246&t5081ot47yb8p9khx80");
        }

        //延迟初始化
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                QbSdk.initX5Environment(context, null);

            }
        }, 2000);

        upgrade(context);

        Timber.e("initThirdPartySDK --> x5 " + (SystemClock.elapsedRealtime() - endSt));
        endSt = SystemClock.elapsedRealtime();
        GAdSdk.init(context, "jSgmbuon650qyNjGUVuLZg==");

        //闪验
        if (!TextUtils.isEmpty(BuildConfig.SHANYAN_APPID)) {
            OneKeyLoginManager.getInstance().init(context, BuildConfig.SHANYAN_APPID, new InitListener() {
                @Override
                public void getInitStatus(int code, String result) {

                    Timber.e("getInitStatus   " + code + "   " + result);

                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            //判断是否登录
                            if (!DataCenter.get().hasLogin()) {
                                OneKeyLoginManager.getInstance().getPhoneInfo(new GetPhoneInfoListener() {
                                    @Override
                                    public void getPhoneInfoStatus(int code, String result) {
                                        Timber.e("getPhoneInfoStatus   " + code + "   " + result);
                                        if (result != null && !result.contains("成功")) {
                                            BizReport.sendException(BizReport.SY_ONEKEY_PRE_ERROR, code + ":" + result);
                                        }

                                    }
                                });
                            }
                        }
                    }, 3000);

                }
            });
        }

        Timber.e("initThirdPartySDK --> upgrade " + (SystemClock.elapsedRealtime() - endSt));

    }


    private void upgrade(Context context) {
        //更新
        MessageCenter.INSTANCE.hookUpdateListener();
        UpgradeConfigure.init(context);
    }


    private void initController() {
        final Context context = getContext();
        GlobalConfigManager.getInstance().init(context);

        LocManager.getInstance().init(context).loadLocation();

        DataCenter.get();


        WeatherManager.getInstance().init(context);

        MessageCenter.INSTANCE.startObserver();

        PreLoader.load();
        registerActivityLifecycleCallback(new Application.ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                PushAgent.getInstance(context).onAppStart();
                if (VERSION.SDK_INT < VERSION_CODES.M) {
                    //推啊 广告特殊处理
                    if (activity instanceof LionActivity) {
                        UiUtils.INSTANCE.setStatusBarLight(activity, false);
                    } else {
                        UiUtils.INSTANCE.setStatusBarLight(activity, true);
                    }

                }

            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {
                if (activity != null) {
                    StatService.onResume(activity);
                    //MobclickAgent.onResume(activity);
                }
            }

            @Override
            public void onActivityPaused(Activity activity) {
                if (activity != null) {
                    StatService.onPause(activity);
                    //MobclickAgent.onPause(activity);
                }
            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });
    }


    private static class CrashReportingTree extends Timber.Tree {
        @Override

        protected boolean isLoggable(@Nullable String tag, int priority) {
            return GlobalConfigManager.getInstance().getDebugConfig().openLog;
        }

//    @Override
//    protected void log(int priority, String tag, @NotNull String message, Throwable t) {
//      super.log(priority, tag, message, t);
//
//      Logan.w(message,1);
//      Logan.f();
//    }

        @Override
        protected void log(int priority, String tag, @NonNull String message, Throwable t) {
            if (priority == Log.VERBOSE || priority == Log.DEBUG) {
                return;
            }
            if (t != null) {
                if (priority == Log.ERROR) {
                    Log.e(tag, message, t);
                } else if (priority == Log.WARN) {
                    Log.w(tag, message, t);
                }
            }

        }
    }

}
